package com.yishan.filter;

import com.alibaba.fastjson2.JSON;
import com.yishan.domain.User;
import com.yishan.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter
//@Component
public class TokenFilter implements Filter {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        if(requestURI.equals("/token/get/token")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String token = request.getHeader("token");
        if (redisTemplate.hasKey(token)) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        Response res=Response.error("非法操作");
        String json = JSON.toJSONString(res);
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
